package org.cmg.study.spring.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author CMG
 * @version 1.0
 * @cLassName LoginInterceptor
 * @description
 * @date 2021/9/6 10:41
 **/
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle方法在控制器的处理请求方法调用之前执行");
        //获取请求URL
        String url = request.getRequestURI();
        //login.jsp或登陆请求放行，不拦截
        if(url.indexOf("/toLogin") >= 0 || url.indexOf("/login") >= 0){
            return true;
        }
        //获取session
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("user");
        if(null != obj){
            return true;
        }
        //没有登录且不是登录页面，跳转到登陆页面，并且给出提示错误信息
        request.setAttribute("msg", "还没登录，请先登录！");
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // TODO postHandle方法在控制器的处理请求方法调用之后，解析视图之前执行
        System.out.println("postHandle方法在控制器的处理请求方法调用之后，解析视图之前执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // TODO afterCompletion方法在控制器的处理请求方法执行完成后执行，即视图渲染结束之后执行
        System.out.println("afterCompletion方法在控制器的处理请求方法执行完成后执行，即视图渲染结束之后执行");
    }
}
